Connectivity Software User's Guide and Reference
Rapid Toolkit for Sparkplug Push Data Consumption Model
Rapid Toolkit for Sparkplug > Concepts > Developing Sparkplug Edge Nodes > Rapid Toolkit for Sparkplug Data Provision And Consumption Models > Rapid Toolkit for Sparkplug Push Data Consumption Model
In This Topic

General

In the push data consumption model, you write a method that fulfills the Sparkplug commands received ("Writes"). Rapid Toolkit for Sparkplug calls this method (pushes the data) when needed.

This is the more common data consumption model.

Your task as a developer is to provide the code for handling the Write request by either adding an event handler for the Write Event, or overriding the OnWrite Method. The code for handling the data push can be attached to each metric separately, or you can use a common code on the parent level - for example, a Sparkplug device object can have code that handles all Writes for the metrics contained in the device.

In order to indicate that you have handled the Write request, your code will call the HandleAndReturn Method on the event arguments object. Note that if you use the extension methods for configuration of metrics, the event handler added by the extension methods already does this for you.

The following picture illustrates how the push data consumption model works.

Extension Methods for Configuration

Rapid Toolkit for Sparkplug provides extension methods that allow you to define metrics that use the push data consumption model easily, without having to deal with method overrides, or handle events. This is described in the Sparkplug Metric Configuration article. Typically, you will use some overload of the WriteFunction, WriteValueAction or WriteValueFunction method to configure the metric for the push data consumption model. With these methods, you use .NET functions (Func<...,TResult> Delegate) or actions (Action Delegate) to specify the code that handles the request. The following example illustrates the use of the WriteValueAction method.

.NET

// This example shows how to use an action to define what happens when a Sparkplug application sends data to a metric. This
// is an example of the push data consumption model.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
// data into the metric.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using OpcLabs.EasySparkplug;
using System;

namespace SparkplugDocExamples.EdgeNode._SparkplugMetric
{
    partial class WriteValueAction
    {
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Create a writable metric and add an action that will be executed when the metric is written to.
            edgeNode.Add(new SparkplugMetric("WriteToThisMetric").WriteValueAction<int>(value =>
                Console.WriteLine($"Value written: {value}")));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }
    }
}
' This example shows how to use an action to define what happens when a Sparkplug application sends data to a metric. This
' is an example of the push data consumption model.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
' data into the metric.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug

Namespace Global.SparkplugDocExamples.EdgeNode._SparkplugMetric
    Partial Class WriteValueAction
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged,
                Sub(sender, eventArgs)
                    ' Display the new connection state (such as when the connection to the broker succeeds or fails).
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
                End Sub

            ' Create a writable metric and add an action that will be executed when the metric is written to.
            edgeNode.Add(New SparkplugMetric("WriteToThisMetric").WriteValueAction(Of Integer)(
                Sub(value)
                    Console.WriteLine($"Value written: {value}")
                End Sub))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub
    End Class
End Namespace

 

How do you choose between these three extension methods?

The following example illustrates the use of the WriteValueFunction method for a metric that forces its value to be within certain range.

.NET

// This example shows how to use a function to define what happens with the value when a Sparkplug application sends data to
// a metric. This is an example of the push data consumption model.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
// data into the metric.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using OpcLabs.EasySparkplug;
using System;

namespace SparkplugDocExamples.EdgeNode._SparkplugMetric
{
    partial class WriteValueFunction
    {
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate the edge node object and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Create a writable metric and add a function that will be called when the metric is written to. The function
            // returns a boolean that indicates whether the Write operation was successful. We have chosen to only allow
            // non-negative values to be written to the metric. Note that the outcome is used internally, and is not
            // available to the Sparkplug application that has sent the data to the metric.
            edgeNode.Add(new SparkplugMetric("WriteToThisMetric").WriteValueFunction<int>(
                value =>
                {
                    if (value < 0)
                    {
                        Console.WriteLine($"Value rejected: {value}");
                        return false;
                    }
                    Console.WriteLine($"Value written: {value}");
                    return true;    // success
                }));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }
    }
}
' This example shows how to use a function to define what happens with the value when a Sparkplug application sends data to
' a metric. This is an example of the push data consumption model.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
' data into the metric.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug

Namespace Global.SparkplugDocExamples.EdgeNode._SparkplugMetric
    Partial Class WriteValueFunction
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate the edge node object and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged,
                Sub(sender, eventArgs)
                    ' Display the new connection state (such as when the connection to the broker succeeds or fails).
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
                End Sub

            ' Create a writable metric and add a function that will be called when the metric is written to. The function
            ' returns a boolean that indicates whether the Write operation was successful. We have chosen to only allow
            ' non-negative values to be written to the metric. Note that the outcome is used internally, and is not
            ' available to the Sparkplug application that has sent the data to the metric.
            edgeNode.Add(New SparkplugMetric("WriteToThisMetric").WriteValueFunction(Of Integer)(
                Function(value)
                    If value < 0 Then
                        Console.WriteLine($"Value rejected: {value}")
                        Return False
                    End If
                    Console.WriteLine($"Value written: {value}")
                    Return True ' success
                End Function))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub
    End Class
End Namespace

 

If the metric should also support writing of the timestamp, you will use the WriteFunction method.

Handling Requests on Higher Levels

If your Sparkplug edge node or device has groups of metrics with basically the same behavior, you would probably want to specify the behavior just once, and not with every metric. In such case, you cannot use the extension methods for metric configuration (described above), and need to define the behavior by handling the Write Event, or overriding the OnWrite Method, on the parent level - in our example, the level of the edge node. The following examples illustrate these approaches.

Example: Examples - Sparkplug Edge Node - Writing different metrics by a single handler

Example: Examples - Sparkplug Edge Node - Metrics writing by method override

Data Type Considerations 

See Sparkplug Metric Data Type Considerations.

 

Sparkplug is a trademark of Eclipse Foundation, Inc. "MQTT" is a trademark of the OASIS Open standards consortium. Other related terms are trademarks of their respective owners. Any use of these terms on this site is for descriptive purposes only and does not imply any sponsorship, endorsement or affiliation.

See Also